'use strict';

/**
 * 每日运营通知（统计结果通知）
 *    统计指标 {{thing1.DATA}}
 *    统计内容 {{thing2.DATA}}
 */
const MSG_KEY_DAILY_NOTICE = "MA5gAkd1FUb597yAYyY_GoNk9GE3THZeq0NKZmI31FY";

/**
 * 每日运营页面
 */
const PAGE_URL_DAILY = "pages/launch/welcome";

/** 小程序的AppID */
const MP_APP_ID = "wx6e0575f65cf58e81";

/** 小程序的Secret */
const MP_APP_SECRET = "83efe2e372b78bbb7578556257f55baa";

// 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版
// const JUMP_TYPE = "developer";  // 开发版
const JUMP_TYPE = "trial";  // 体验版
// const JUMP_TYPE = "formal"; // 正式版

// 测试
const IS_FOR_TEST = true;
// const IS_FOR_TEST = false;

/** 内部平台管理员的信息 */
const SYSTEM_ADMINS = [
	{ openId: 'owT-q6_hJjasXVp3jfHqBcGVH3tY' }, 
	{ openId: 'owT-q6_XNA2U2NPS9ZcZmUcVFfkQ' },
];


module.exports = {
	_before: function () { // 通用预处理器
	 
	},
	
	say(str){
		return{
			code:"200",
			data:str
		}
	},
	
	async getMpAccessToken() {
		let url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + MP_APP_ID + "&secret=" + MP_APP_SECRET;
		// console.log(url);
		const res = await uniCloud.httpclient.request(url, {
			method: "GET",
			dataType: "json", // 此处指定为json表示将此请求的返回值解析为json
			timeout: 30000
		});
		// console.log("res",res);
		return res.data.access_token;
	},
	
	async sendMpMessage(openId, templateId, data, page, accessToken) {
		let url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
		let sendData = {
			"touser": openId, 
			"template_id": templateId,
			"data": data,
			"miniprogram_state": JUMP_TYPE,  // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版
			"lang": "zh_CN"
		}
		if (page != null) {
			sendData['page'] = page
		}
		console.log('sendData:', JSON.stringify(sendData))
		const res = await uniCloud.httpclient.request(url, {
			method: "POST",
			dataType: "json", // 此处指定为json表示将此请求的返回值解析为json
			timeout: 30000, 
			data: JSON.stringify(sendData)
		});
		console.log("res",res);
		return res;
	},
	
	// 给用户发送每日运营通知
	async sendDailyMpMessageToUser() {
		let accessToken = await this.getMpAccessToken();
		console.log('accessToken=', accessToken);
		
		// 查询所有会员用户，逐一发送订阅消息通知
		const db = uniCloud.database();
		const dbCmd = db.command;
		const res = await db.collection("mp-user").where({ isMember: true }).field('_id,openId,isMember').get()
		// console.log('mp-user res:', res);
		for (var i = 0; i < res.data.length; i++) {
			let userInfo = res.data[i];
			// console.log('userInfo:', userInfo);
			// 'userId == "' + userInfo._id + '" && createDate >= new Date().getTime()'
			
			// let customerCount = await db.collection("mp-customer").where({ 
			// 	userId: userInfo._id,
			// 	createDate: dbCmd.aggregate.gte(1701134957120)
			// }).count();
			 
			let customerCount = await db.collection("mp-customer").where({
				userId: userInfo._id,
				createDate: dbCmd.aggregate.gte(new Date().getTime())
			}).count();
			console.log('userId:', userInfo._id);
			console.log('customerCount:', customerCount);
			
			// 每日运营通知（统计结果通知）
			let sendData = {
				// 统计指标 {{thing1.DATA}}
				"thing1": {
					"value": "每日运营"
				},
				// 统计内容 {{thing2.DATA}}
				"thing2": {
					"value": "今日新增客户：" + customerCount.total + "人"
				}
			};
			// console.log('sendData:', sendData);
			
			if (IS_FOR_TEST) { 
				// 测试，只发内部开发账号
				// 只发内部管理员
				let isIn = false;
				for (var i = 0; i < SYSTEM_ADMINS.length; i++) {
					if (userInfo.openId == SYSTEM_ADMINS[i].openId) {
						isIn = true;
						break;
					}
				}
				if (isIn) {
					let result = await this.sendMpMessage(
						userInfo.openId, 
						MSG_KEY_DAILY_NOTICE, 
						sendData, 
						PAGE_URL_DAILY,
						accessToken
					);
					console.log('result:', result);
				}
			} else {
				// 正式，全量发送
				let result = await this.sendMpMessage(
					userInfo.openId, 
					MSG_KEY_DAILY_NOTICE, 
					sendData, 
					PAGE_URL_DAILY,
					accessToken
				);
				console.log('result:', result);
			}
		}
	},
	
	async sendDailyMpMessageForTest(userInfo) {
		let accessToken = await this.getMpAccessToken();
		console.log('accessToken=', accessToken);
		
		// 查询所有会员用户，逐一发送订阅消息通知
		const db = uniCloud.database();
		const dbCmd = db.command;
		
		let customerCount = await db.collection("mp-customer").where({
			userId: userInfo._id,
			createDate: dbCmd.aggregate.gte(new Date().getTime())
		}).count();
		console.log('userId:', userInfo._id);
		console.log('customerCount:', customerCount);
		
		// 每日运营通知（统计结果通知）
		let sendData = {
			// 统计指标 {{thing1.DATA}}
			"thing1": {
				"value": "每日运营通知"  
			},
			// 统计内容 {{thing2.DATA}}
			"thing2": {
				"value": "今日新增客户：" + customerCount.total + "人"
			}
		};
		// console.log('sendData:', sendData);
		let result = await this.sendMpMessage(
			userInfo.openId, 
			MSG_KEY_DAILY_NOTICE, 
			sendData, 
			PAGE_URL_DAILY, 
			accessToken
		);
		console.log('result:', result)
	},
	
	async main(event, context) {
		//event为客户端上传的参数
		console.log('event : ', event);
		
		// 给用户发送每日运营通知
		await this.sendDailyMpMessageToUser();
		
		//返回数据给客户端
		return event;
	}
}